home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Modules / _tkinter.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-08-03  |  45.6 KB  |  2,277 lines

  1. /***********************************************************
  2. Copyright (C) 1994 Steen Lumholt.
  3. ******************************************************************/
  4.  
  5. /* _tkinter.c -- Interface to libtk.a and libtcl.a. */
  6.  
  7. /* TCL/TK VERSION INFO:
  8.  
  9.     Only Tcl/Tk 8.0 and later are supported.  Older versions are not
  10.     supported.  (Use Python 1.5.2 if you cannot upgrade your Tcl/Tk
  11.     libraries.)
  12. */
  13.  
  14. /* XXX Further speed-up ideas, involving Tcl 8.0 features:
  15.  
  16.    - In Tcl_Call(), create Tcl objects from the arguments, possibly using
  17.    intelligent mappings between Python objects and Tcl objects (e.g. ints,
  18.    floats and Tcl window pointers could be handled specially).
  19.  
  20.    - Register a new Tcl type, "Python callable", which can be called more
  21.    efficiently and passed to Tcl_EvalObj() directly (if this is possible).
  22.  
  23. */
  24.  
  25.  
  26. #include "Python.h"
  27. #include <ctype.h>
  28.  
  29. #ifdef WITH_THREAD
  30. #include "pythread.h"
  31. #endif
  32.  
  33. #ifdef MS_WINDOWS
  34. #include <windows.h>
  35. #endif
  36.  
  37. #ifdef macintosh
  38. #define MAC_TCL
  39. #include "myselect.h"
  40. #endif
  41.  
  42. #ifdef PYOS_OS2
  43. #include "myselect.h"
  44. #endif
  45.  
  46. #include <tcl.h>
  47. #include <tk.h>
  48.  
  49. #define TKMAJORMINOR (TK_MAJOR_VERSION*1000 + TK_MINOR_VERSION)
  50.  
  51. #if TKMAJORMINOR < 8000
  52. #error "Tk older than 8.0 not supported"
  53. #endif
  54.  
  55. #if defined(macintosh)
  56. /* Sigh, we have to include this to get at the tcl qd pointer */
  57. #include <tkMac.h>
  58. /* And this one we need to clear the menu bar */
  59. #include <Menus.h>
  60. #endif
  61.  
  62. #if !defined(MS_WINDOWS)
  63. #define HAVE_CREATEFILEHANDLER
  64. #endif
  65.  
  66. #ifdef HAVE_CREATEFILEHANDLER
  67.  
  68. /* Tcl_CreateFileHandler() changed several times; these macros deal with the
  69.    messiness.  In Tcl 8.0 and later, it is not available on Windows (and on
  70.    Unix, only because Jack added it back); when available on Windows, it only
  71.    applies to sockets. */
  72.  
  73. #ifdef MS_WINDOWS
  74. #define FHANDLETYPE TCL_WIN_SOCKET
  75. #else
  76. #define FHANDLETYPE TCL_UNIX_FD
  77. #endif
  78.  
  79. /* If Tcl can wait for a Unix file descriptor, define the EventHook() routine
  80.    which uses this to handle Tcl events while the user is typing commands. */
  81.  
  82. #if FHANDLETYPE == TCL_UNIX_FD
  83. #define WAIT_FOR_STDIN
  84. #endif
  85.  
  86. #endif /* HAVE_CREATEFILEHANDLER */
  87.  
  88. #ifdef MS_WINDOWS
  89. #include <conio.h>
  90. #define WAIT_FOR_STDIN
  91. #endif
  92.  
  93. #ifdef WITH_THREAD
  94.  
  95. /* The threading situation is complicated.  Tcl is not thread-safe, except for
  96.    Tcl 8.1, which will probably remain in alpha status for another 6 months
  97.    (and the README says that Tk will probably remain thread-unsafe forever).
  98.    So we need to use a lock around all uses of Tcl.  Previously, the Python
  99.    interpreter lock was used for this.  However, this causes problems when
  100.    other Python threads need to run while Tcl is blocked waiting for events.
  101.  
  102.    To solve this problem, a separate lock for Tcl is introduced.  Holding it
  103.    is incompatible with holding Python's interpreter lock.  The following four
  104.    macros manipulate both locks together.
  105.  
  106.    ENTER_TCL and LEAVE_TCL are brackets, just like Py_BEGIN_ALLOW_THREADS and
  107.    Py_END_ALLOW_THREADS.  They should be used whenever a call into Tcl is made
  108.    that could call an event handler, or otherwise affect the state of a Tcl
  109.    interpreter.  These assume that the surrounding code has the Python
  110.    interpreter lock; inside the brackets, the Python interpreter lock has been 
  111.    released and the lock for Tcl has been acquired.
  112.  
  113.    Sometimes, it is necessary to have both the Python lock and the Tcl lock.
  114.    (For example, when transferring data from the Tcl interpreter result to a
  115.    Python string object.)  This can be done by using different macros to close
  116.    the ENTER_TCL block: ENTER_OVERLAP reacquires the Python lock (and restores
  117.    the thread state) but doesn't release the Tcl lock; LEAVE_OVERLAP_TCL
  118.    releases the Tcl lock.
  119.  
  120.    By contrast, ENTER_PYTHON and LEAVE_PYTHON are used in Tcl event
  121.    handlers when the handler needs to use Python.  Such event handlers are
  122.    entered while the lock for Tcl is held; the event handler presumably needs
  123.    to use Python.  ENTER_PYTHON releases the lock for Tcl and acquires
  124.    the Python interpreter lock, restoring the appropriate thread state, and
  125.    LEAVE_PYTHON releases the Python interpreter lock and re-acquires the lock
  126.    for Tcl.  It is okay for ENTER_TCL/LEAVE_TCL pairs to be contained inside
  127.    the code between ENTER_PYTHON and LEAVE_PYTHON.
  128.  
  129.    These locks expand to several statements and brackets; they should not be
  130.    used in branches of if statements and the like.
  131.  
  132. */
  133.  
  134. static PyThread_type_lock tcl_lock = 0;
  135. static PyThreadState *tcl_tstate = NULL;
  136.  
  137. #define ENTER_TCL \
  138.     { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \
  139.         PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate;
  140.  
  141. #define LEAVE_TCL \
  142.     tcl_tstate = NULL; PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS}
  143.  
  144. #define ENTER_OVERLAP \
  145.     Py_END_ALLOW_THREADS
  146.  
  147. #define LEAVE_OVERLAP_TCL \
  148.     tcl_tstate = NULL; PyThread_release_lock(tcl_lock); }
  149.  
  150. #define ENTER_PYTHON \
  151.     { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \
  152.             PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); }
  153.  
  154. #define LEAVE_PYTHON \
  155.     { PyThreadState *tstate = PyEval_SaveThread(); \
  156.             PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; }
  157.  
  158. #else
  159.  
  160. #define ENTER_TCL
  161. #define LEAVE_TCL
  162. #define ENTER_OVERLAP
  163. #define LEAVE_OVERLAP_TCL
  164. #define ENTER_PYTHON
  165. #define LEAVE_PYTHON
  166.  
  167. #endif
  168.  
  169. #ifdef macintosh
  170.  
  171. /*
  172. ** Additional cruft needed by Tcl/Tk on the Mac.
  173. ** This is for Tcl 7.5 and Tk 4.1 (patch release 1).
  174. */
  175.  
  176. /* ckfree() expects a char* */
  177. #define FREECAST (char *)
  178.  
  179. #include <Events.h> /* For EventRecord */
  180.  
  181. typedef int (*TclMacConvertEventPtr) Py_PROTO((EventRecord *eventPtr));
  182. void Tcl_MacSetEventProc Py_PROTO((TclMacConvertEventPtr procPtr));
  183. int TkMacConvertEvent Py_PROTO((EventRecord *eventPtr));
  184.  
  185. staticforward int PyMacConvertEvent Py_PROTO((EventRecord *eventPtr));
  186.  
  187. #if defined(__CFM68K__) && !defined(__USING_STATIC_LIBS__)
  188.     #pragma import on
  189. #endif
  190.  
  191. #include <SIOUX.h>
  192. extern int SIOUXIsAppWindow(WindowPtr);
  193.  
  194. #if defined(__CFM68K__) && !defined(__USING_STATIC_LIBS__)
  195.     #pragma import reset
  196. #endif
  197. #endif /* macintosh */
  198.  
  199. #ifndef FREECAST
  200. #define FREECAST (char *)
  201. #endif
  202.  
  203. /**** Tkapp Object Declaration ****/
  204.  
  205. staticforward PyTypeObject Tkapp_Type;
  206.  
  207. typedef struct {
  208.     PyObject_HEAD
  209.     Tcl_Interp *interp;
  210. } TkappObject;
  211.  
  212. #define Tkapp_Check(v) ((v)->ob_type == &Tkapp_Type)
  213. #define Tkapp_Interp(v) (((TkappObject *) (v))->interp)
  214. #define Tkapp_Result(v) (((TkappObject *) (v))->interp->result)
  215.  
  216. #define DEBUG_REFCNT(v) (printf("DEBUG: id=%p, refcnt=%i\n", \
  217. (void *) v, ((PyObject *) v)->ob_refcnt))
  218.  
  219.  
  220.  
  221. /**** Error Handling ****/
  222.  
  223. static PyObject *Tkinter_TclError;
  224. static int quitMainLoop = 0;
  225. static int errorInCmd = 0;
  226. static PyObject *excInCmd;
  227. static PyObject *valInCmd;
  228. static PyObject *trbInCmd;
  229.  
  230.  
  231.  
  232. static PyObject *
  233. Tkinter_Error(v)
  234.     PyObject *v;
  235. {
  236.     PyErr_SetString(Tkinter_TclError, Tkapp_Result(v));
  237.     return NULL;
  238. }
  239.  
  240.  
  241.  
  242. /**** Utils ****/
  243.  
  244. #ifdef WITH_THREAD
  245. #ifndef MS_WINDOWS
  246. #include "mytime.h"
  247. #include "myselect.h"
  248.  
  249. /* Millisecond sleep() for Unix platforms. */
  250.  
  251. static void
  252. Sleep(milli)
  253.     int milli;
  254. {
  255.     /* XXX Too bad if you don't have select(). */
  256.     struct timeval t;
  257.     double frac;
  258.     t.tv_sec = milli/1000;
  259.     t.tv_usec = (milli%1000) * 1000;
  260.     select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
  261. }
  262. #endif /* MS_WINDOWS */
  263. #endif /* WITH_THREAD */
  264.  
  265.  
  266. static char *
  267. AsString(value, tmp)
  268.     PyObject *value;
  269.     PyObject *tmp;
  270. {
  271.     if (PyString_Check(value))
  272.         return PyString_AsString(value);
  273.     else {
  274.         PyObject *v = PyObject_Str(value);
  275.         PyList_Append(tmp, v);
  276.         Py_DECREF(v);
  277.         return PyString_AsString(v);
  278.     }
  279. }
  280.  
  281.  
  282.  
  283. #define ARGSZ 64
  284.  
  285. static char *
  286. Merge(args)
  287.     PyObject *args;
  288. {
  289.     PyObject *tmp = NULL;
  290.     char *argvStore[ARGSZ];
  291.     char **argv = NULL;
  292.     int fvStore[ARGSZ];
  293.     int *fv = NULL;
  294.     int argc = 0, i;
  295.     char *res = NULL;
  296.  
  297.     if (!(tmp = PyList_New(0)))
  298.         return NULL;
  299.  
  300.     argv = argvStore;
  301.     fv = fvStore;
  302.  
  303.     if (args == NULL)
  304.         argc = 0;
  305.  
  306.     else if (!PyTuple_Check(args)) {
  307.         argc = 1;
  308.         fv[0] = 0;
  309.         argv[0] = AsString(args, tmp);
  310.     }
  311.     else {
  312.         argc = PyTuple_Size(args);
  313.  
  314.         if (argc > ARGSZ) {
  315.             argv = (char **)ckalloc(argc * sizeof(char *));
  316.             fv = (int *)ckalloc(argc * sizeof(int));
  317.             if (argv == NULL || fv == NULL) {
  318.                 PyErr_NoMemory();
  319.                 goto finally;
  320.             }
  321.         }
  322.  
  323.         for (i = 0; i < argc; i++) {
  324.             PyObject *v = PyTuple_GetItem(args, i);
  325.             if (PyTuple_Check(v)) {
  326.                 fv[i] = 1;
  327.                 if (!(argv[i] = Merge(v)))
  328.                     goto finally;
  329.             }
  330.             else if (v == Py_None) {
  331.                 argc = i;
  332.                 break;
  333.             }
  334.             else {
  335.                 fv[i] = 0;
  336.                 argv[i] = AsString(v, tmp);
  337.             }
  338.         }
  339.     }
  340.     res = Tcl_Merge(argc, argv);
  341.  
  342.   finally:
  343.     for (i = 0; i < argc; i++)
  344.         if (fv[i]) {
  345.             ckfree(argv[i]);
  346.         }
  347.     if (argv != argvStore)
  348.         ckfree(FREECAST argv);
  349.     if (fv != fvStore)
  350.         ckfree(FREECAST fv);
  351.  
  352.     Py_DECREF(tmp);
  353.     return res;
  354. }
  355.  
  356.  
  357.  
  358. static PyObject *
  359. Split(list)
  360.     char *list;
  361. {
  362.     int argc;
  363.     char **argv;
  364.     PyObject *v;
  365.  
  366.     if (list == NULL) {
  367.         Py_INCREF(Py_None);
  368.         return Py_None;
  369.     }
  370.  
  371.     if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
  372.         /* Not a list.
  373.          * Could be a quoted string containing funnies, e.g. {"}.
  374.          * Return the string itself.
  375.          */
  376.         return PyString_FromString(list);
  377.     }
  378.  
  379.     if (argc == 0)
  380.         v = PyString_FromString("");
  381.     else if (argc == 1)
  382.         v = PyString_FromString(argv[0]);
  383.     else if ((v = PyTuple_New(argc)) != NULL) {
  384.         int i;
  385.         PyObject *w;
  386.  
  387.         for (i = 0; i < argc; i++) {
  388.             if ((w = Split(argv[i])) == NULL) {
  389.                 Py_DECREF(v);
  390.                 v = NULL;
  391.                 break;
  392.             }
  393.             PyTuple_SetItem(v, i, w);
  394.         }
  395.     }
  396.     Tcl_Free(FREECAST argv);
  397.     return v;
  398. }
  399.  
  400.  
  401.  
  402. /**** Tkapp Object ****/
  403.  
  404. #ifndef WITH_APPINIT
  405. int
  406. Tcl_AppInit(interp)
  407.     Tcl_Interp *interp;
  408. {
  409.     Tk_Window main;
  410.  
  411.     main = Tk_MainWindow(interp);
  412.     if (Tcl_Init(interp) == TCL_ERROR) {
  413.         PySys_WriteStderr("Tcl_Init error: %s\n", interp->result);
  414.         return TCL_ERROR;
  415.     }
  416.     if (Tk_Init(interp) == TCL_ERROR) {
  417.         PySys_WriteStderr("Tk_Init error: %s\n", interp->result);
  418.         return TCL_ERROR;
  419.     }
  420.     return TCL_OK;
  421. }
  422. #endif /* !WITH_APPINIT */
  423.  
  424.  
  425.  
  426.  
  427. /* Initialize the Tk application; see the `main' function in
  428.  * `tkMain.c'.
  429.  */
  430.  
  431. static void EnableEventHook(); /* Forward */
  432. static void DisableEventHook(); /* Forward */
  433.  
  434. static TkappObject *
  435. Tkapp_New(screenName, baseName, className, interactive)
  436.     char *screenName;
  437.     char *baseName;
  438.     char *className;
  439.     int interactive;
  440. {
  441.     TkappObject *v;
  442.     char *argv0;
  443.   
  444.     v = PyObject_New(TkappObject, &Tkapp_Type);
  445.     if (v == NULL)
  446.         return NULL;
  447.  
  448.     v->interp = Tcl_CreateInterp();
  449.  
  450. #if defined(macintosh)
  451.     /* This seems to be needed */
  452.     ClearMenuBar();
  453.     TkMacInitMenus(v->interp);
  454. #endif
  455.     /* Delete the 'exit' command, which can screw things up */
  456.     Tcl_DeleteCommand(v->interp, "exit");
  457.  
  458.     if (screenName != NULL)
  459.         Tcl_SetVar2(v->interp, "env", "DISPLAY",
  460.                 screenName, TCL_GLOBAL_ONLY);
  461.  
  462.     if (interactive)
  463.         Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY);
  464.     else
  465.         Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
  466.  
  467.     /* This is used to get the application class for Tk 4.1 and up */
  468.     argv0 = (char*)ckalloc(strlen(className) + 1);
  469.     if (!argv0) {
  470.         PyErr_NoMemory();
  471.         Py_DECREF(v);
  472.         return NULL;
  473.     }
  474.  
  475.     strcpy(argv0, className);
  476.     if (isupper((int)(argv0[0])))
  477.         argv0[0] = tolower(argv0[0]);
  478.     Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
  479.     ckfree(argv0);
  480.  
  481.     if (Tcl_AppInit(v->interp) != TCL_OK)
  482.         return (TkappObject *)Tkinter_Error((PyObject *)v);
  483.  
  484.     EnableEventHook();
  485.  
  486.     return v;
  487. }
  488.  
  489.  
  490.  
  491. /** Tcl Eval **/
  492.  
  493. #if TKMAJORMINOR >= 8001
  494. #define USING_OBJECTS
  495. #endif
  496.  
  497. #ifdef USING_OBJECTS
  498.  
  499. static Tcl_Obj*
  500. AsObj(value)
  501.     PyObject *value;
  502. {
  503.     Tcl_Obj *result;
  504.  
  505.     if (PyString_Check(value))
  506.         return Tcl_NewStringObj(PyString_AS_STRING(value),
  507.                     PyString_GET_SIZE(value));
  508.     else if (PyInt_Check(value))
  509.         return Tcl_NewLongObj(PyInt_AS_LONG(value));
  510.     else if (PyFloat_Check(value))
  511.         return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
  512.     else if (PyTuple_Check(value)) {
  513.         Tcl_Obj **argv = (Tcl_Obj**)
  514.             ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*));
  515.         int i;
  516.         if(!argv)
  517.           return 0;
  518.         for(i=0;i<PyTuple_Size(value);i++)
  519.           argv[i] = AsObj(PyTuple_GetItem(value,i));
  520.         result = Tcl_NewListObj(PyTuple_Size(value), argv);
  521.         ckfree(FREECAST argv);
  522.         return result;
  523.     }
  524.     else if (PyUnicode_Check(value)) {
  525. #if TKMAJORMINOR <= 8001
  526.         /* In Tcl 8.1 we must use UTF-8 */
  527.         PyObject* utf8 = PyUnicode_AsUTF8String (value);
  528.         if (!utf8)
  529.             return 0;
  530.         result = Tcl_NewStringObj (PyString_AS_STRING (utf8),
  531.                      PyString_GET_SIZE (utf8));
  532.         Py_DECREF(utf8);
  533.         return result;
  534. #else /* TKMAJORMINOR > 8001 */
  535.         /* In Tcl 8.2 and later, use Tcl_NewUnicodeObj() */
  536.         if (sizeof(Py_UNICODE) != sizeof(Tcl_UniChar)) {
  537.             /* XXX Should really test this at compile time */
  538.             PyErr_SetString(PyExc_SystemError,
  539.                     "Py_UNICODE and Tcl_UniChar differ in size");
  540.             return 0;
  541.         }
  542.         return Tcl_NewUnicodeObj(PyUnicode_AS_UNICODE(value),
  543.                      PyUnicode_GET_SIZE(value));
  544. #endif /* TKMAJORMINOR > 8001 */
  545.     }
  546.     else {
  547.         PyObject *v = PyObject_Str(value);
  548.         if (!v)
  549.             return 0;
  550.         result = AsObj(v);
  551.         Py_DECREF(v);
  552.         return result;
  553.     }
  554. }
  555.  
  556. static PyObject *
  557. Tkapp_Call(self, args)
  558.     PyObject *self;
  559.     PyObject *args;
  560. {
  561.     Tcl_Obj *objStore[ARGSZ];
  562.     Tcl_Obj **objv = NULL;
  563.     int objc = 0, i;
  564.     PyObject *res = NULL;
  565.     Tcl_Interp *interp = Tkapp_Interp(self);
  566.     /* Could add TCL_EVAL_GLOBAL if wrapped by GlobalCall... */
  567.     int flags = TCL_EVAL_DIRECT;
  568.  
  569.     objv = objStore;
  570.  
  571.     if (args == NULL)
  572.         objc = 0;
  573.  
  574.     else if (!PyTuple_Check(args)) {
  575.         objc = 1;
  576.         objv[0] = AsObj(args);
  577.         if (objv[0] == 0)
  578.             goto finally;
  579.         Tcl_IncrRefCount(objv[0]);
  580.     }
  581.     else {
  582.         objc = PyTuple_Size(args);
  583.  
  584.         if (objc > ARGSZ) {
  585.             objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *));
  586.             if (objv == NULL) {
  587.                 PyErr_NoMemory();
  588.                 goto finally;
  589.             }
  590.         }
  591.  
  592.         for (i = 0; i < objc; i++) {
  593.             PyObject *v = PyTuple_GetItem(args, i);
  594.             if (v == Py_None) {
  595.                 objc = i;
  596.                 break;
  597.             }
  598.             objv[i] = AsObj(v);
  599.             if (!objv[i])
  600.                 goto finally;
  601.             Tcl_IncrRefCount(objv[i]);
  602.         }
  603.     }
  604.  
  605.     ENTER_TCL
  606.  
  607.     i = Tcl_EvalObjv(interp, objc, objv, flags);
  608.  
  609.     ENTER_OVERLAP
  610.     if (i == TCL_ERROR)
  611.         Tkinter_Error(self);
  612.     else {
  613.         /* We could request the object result here, but doing
  614.            so would confuse applications that expect a string. */
  615.         char *s = Tcl_GetStringResult(interp);
  616.         char *p = s;
  617.         /* If the result contains any bytes with the top bit set,
  618.            it's UTF-8 and we should decode it to Unicode */
  619.         while (*p != '\0') {
  620.             if (*p & 0x80)
  621.                 break;
  622.             p++;
  623.         }
  624.         if (*p == '\0')
  625.             res = PyString_FromStringAndSize(s, (int)(p-s));
  626.         else {
  627.             /* Convert UTF-8 to Unicode string */
  628.             p = strchr(p, '\0');
  629.             res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
  630.             if (res == NULL) {
  631.                 PyErr_Clear();
  632.                 res = PyString_FromStringAndSize(s, (int)(p-s));
  633.             }
  634.         }
  635.     }
  636.  
  637.     LEAVE_OVERLAP_TCL
  638.  
  639.   finally:
  640.     for (i = 0; i < objc; i++)
  641.         Tcl_DecrRefCount(objv[i]);
  642.     if (objv != objStore)
  643.         ckfree(FREECAST objv);
  644.     return res;
  645. }
  646.  
  647. #else /* !USING_OBJECTS */
  648.  
  649. static PyObject *
  650. Tkapp_Call(self, args)
  651.     PyObject *self;
  652.     PyObject *args;
  653. {
  654.     /* This is copied from Merge() */
  655.     PyObject *tmp = NULL;
  656.     char *argvStore[ARGSZ];
  657.     char **argv = NULL;
  658.     int fvStore[ARGSZ];
  659.     int *fv = NULL;
  660.     int argc = 0, i;
  661.     PyObject *res = NULL; /* except this has a different type */
  662.     Tcl_CmdInfo info; /* and this is added */
  663.     Tcl_Interp *interp = Tkapp_Interp(self); /* and this too */
  664.  
  665.     if (!(tmp = PyList_New(0)))
  666.         return NULL;
  667.  
  668.     argv = argvStore;
  669.     fv = fvStore;
  670.  
  671.     if (args == NULL)
  672.         argc = 0;
  673.  
  674.     else if (!PyTuple_Check(args)) {
  675.         argc = 1;
  676.         fv[0] = 0;
  677.         argv[0] = AsString(args, tmp);
  678.     }
  679.     else {
  680.         argc = PyTuple_Size(args);
  681.  
  682.         if (argc > ARGSZ) {
  683.             argv = (char **)ckalloc(argc * sizeof(char *));
  684.             fv = (int *)ckalloc(argc * sizeof(int));
  685.             if (argv == NULL || fv == NULL) {
  686.                 PyErr_NoMemory();
  687.                 goto finally;
  688.             }
  689.         }
  690.  
  691.         for (i = 0; i < argc; i++) {
  692.             PyObject *v = PyTuple_GetItem(args, i);
  693.             if (PyTuple_Check(v)) {
  694.                 fv[i] = 1;
  695.                 if (!(argv[i] = Merge(v)))
  696.                     goto finally;
  697.             }
  698.             else if (v == Py_None) {
  699.                 argc = i;
  700.                 break;
  701.             }
  702.             else {
  703.                 fv[i] = 0;
  704.                 argv[i] = AsString(v, tmp);
  705.             }
  706.         }
  707.     }
  708.     /* End code copied from Merge() */
  709.  
  710.     /* All this to avoid a call to Tcl_Merge() and the corresponding call
  711.        to Tcl_SplitList() inside Tcl_Eval()...  It can save a bundle! */
  712.     if (Py_VerboseFlag >= 2) {
  713.         for (i = 0; i < argc; i++)
  714.             PySys_WriteStderr("%s ", argv[i]);
  715.     }
  716.     ENTER_TCL
  717.     info.proc = NULL;
  718.     if (argc < 1 ||
  719.         !Tcl_GetCommandInfo(interp, argv[0], &info) ||
  720.         info.proc == NULL)
  721.     {
  722.         char *cmd;
  723.         cmd = Tcl_Merge(argc, argv);
  724.         i = Tcl_Eval(interp, cmd);
  725.         ckfree(cmd);
  726.     }
  727.     else {
  728.         Tcl_ResetResult(interp);
  729.         i = (*info.proc)(info.clientData, interp, argc, argv);
  730.     }
  731.     ENTER_OVERLAP
  732.     if (info.proc == NULL && Py_VerboseFlag >= 2)
  733.         PySys_WriteStderr("... use TclEval ");
  734.     if (i == TCL_ERROR) {
  735.         if (Py_VerboseFlag >= 2)
  736.             PySys_WriteStderr("... error: '%s'\n",
  737.                 interp->result);
  738.         Tkinter_Error(self);
  739.     }
  740.     else {
  741.         if (Py_VerboseFlag >= 2)
  742.             PySys_WriteStderr("-> '%s'\n", interp->result);
  743.         res = PyString_FromString(interp->result);
  744.     }
  745.     LEAVE_OVERLAP_TCL
  746.  
  747.     /* Copied from Merge() again */
  748.   finally:
  749.     for (i = 0; i < argc; i++)
  750.         if (fv[i]) {
  751.             ckfree(argv[i]);
  752.         }
  753.     if (argv != argvStore)
  754.         ckfree(FREECAST argv);
  755.     if (fv != fvStore)
  756.         ckfree(FREECAST fv);
  757.  
  758.     Py_DECREF(tmp);
  759.     return res;
  760. }
  761.  
  762. #endif /* !USING_OBJECTS */
  763.  
  764. static PyObject *
  765. Tkapp_GlobalCall(self, args)
  766.     PyObject *self;
  767.     PyObject *args;
  768. {
  769.     /* Could do the same here as for Tkapp_Call(), but this is not used
  770.        much, so I can't be bothered.  Unfortunately Tcl doesn't export a
  771.        way for the user to do what all its Global* variants do (save and
  772.        reset the scope pointer, call the local version, restore the saved
  773.        scope pointer). */
  774.  
  775.     char *cmd;
  776.     PyObject *res = NULL;
  777.  
  778.     cmd  = Merge(args);
  779.     if (!cmd)
  780.         PyErr_SetString(Tkinter_TclError, "merge failed");
  781.  
  782.     else {
  783.         int err;
  784.         ENTER_TCL
  785.         err = Tcl_GlobalEval(Tkapp_Interp(self), cmd);
  786.         ENTER_OVERLAP
  787.         if (err == TCL_ERROR)
  788.             res = Tkinter_Error(self);
  789.         else
  790.             res = PyString_FromString(Tkapp_Result(self));
  791.         LEAVE_OVERLAP_TCL
  792.     }
  793.  
  794.     if (cmd)
  795.         ckfree(cmd);
  796.  
  797.     return res;
  798. }
  799.  
  800. static PyObject *
  801. Tkapp_Eval(self, args)
  802.     PyObject *self;
  803.     PyObject *args;
  804. {
  805.     char *script;
  806.     PyObject *res = NULL;
  807.     int err;
  808.   
  809.     if (!PyArg_ParseTuple(args, "s:eval", &script))
  810.         return NULL;
  811.  
  812.     ENTER_TCL
  813.     err = Tcl_Eval(Tkapp_Interp(self), script);
  814.     ENTER_OVERLAP
  815.     if (err == TCL_ERROR)
  816.         res = Tkinter_Error(self);
  817.     else
  818.         res = PyString_FromString(Tkapp_Result(self));
  819.     LEAVE_OVERLAP_TCL
  820.     return res;
  821. }
  822.  
  823. static PyObject *
  824. Tkapp_GlobalEval(self, args)
  825.     PyObject *self;
  826.     PyObject *args;
  827. {
  828.     char *script;
  829.     PyObject *res = NULL;
  830.     int err;
  831.  
  832.     if (!PyArg_ParseTuple(args, "s:globaleval", &script))
  833.         return NULL;
  834.  
  835.     ENTER_TCL
  836.     err = Tcl_GlobalEval(Tkapp_Interp(self), script);
  837.     ENTER_OVERLAP
  838.     if (err == TCL_ERROR)
  839.         res = Tkinter_Error(self);
  840.     else
  841.         res = PyString_FromString(Tkapp_Result(self));
  842.     LEAVE_OVERLAP_TCL
  843.     return res;
  844. }
  845.  
  846. static PyObject *
  847. Tkapp_EvalFile(self, args)
  848.     PyObject *self;
  849.     PyObject *args;
  850. {
  851.     char *fileName;
  852.     PyObject *res = NULL;
  853.     int err;
  854.  
  855.     if (!PyArg_ParseTuple(args, "s:evalfile", &fileName))
  856.         return NULL;
  857.  
  858.     ENTER_TCL
  859.     err = Tcl_EvalFile(Tkapp_Interp(self), fileName);
  860.     ENTER_OVERLAP
  861.     if (err == TCL_ERROR)
  862.         res = Tkinter_Error(self);
  863.  
  864.     else
  865.         res = PyString_FromString(Tkapp_Result(self));
  866.     LEAVE_OVERLAP_TCL
  867.     return res;
  868. }
  869.  
  870. static PyObject *
  871. Tkapp_Record(self, args)
  872.     PyObject *self;
  873.     PyObject *args;
  874. {
  875.     char *script;
  876.     PyObject *res = NULL;
  877.     int err;
  878.  
  879.     if (!PyArg_ParseTuple(args, "s", &script))
  880.         return NULL;
  881.  
  882.     ENTER_TCL
  883.     err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL);
  884.     ENTER_OVERLAP
  885.     if (err == TCL_ERROR)
  886.         res = Tkinter_Error(self);
  887.     else
  888.         res = PyString_FromString(Tkapp_Result(self));
  889.     LEAVE_OVERLAP_TCL
  890.     return res;
  891. }
  892.  
  893. static PyObject *
  894. Tkapp_AddErrorInfo(self, args)
  895.     PyObject *self;
  896.     PyObject *args;
  897. {
  898.     char *msg;
  899.  
  900.     if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg))
  901.         return NULL;
  902.     ENTER_TCL
  903.     Tcl_AddErrorInfo(Tkapp_Interp(self), msg);
  904.     LEAVE_TCL
  905.  
  906.     Py_INCREF(Py_None);
  907.     return Py_None;
  908. }
  909.  
  910.  
  911.  
  912. /** Tcl Variable **/
  913.  
  914. static PyObject *
  915. SetVar(self, args, flags)
  916.     PyObject *self;
  917.     PyObject *args;
  918.     int flags;
  919. {
  920.     char *name1, *name2, *ok, *s;
  921.     PyObject *newValue;
  922.     PyObject *tmp;
  923.  
  924.     tmp = PyList_New(0);
  925.     if (!tmp)
  926.         return NULL;
  927.  
  928.     if (PyArg_ParseTuple(args, "sO:setvar", &name1, &newValue)) {
  929.         /* XXX Merge? */
  930.         s = AsString(newValue, tmp);
  931.         ENTER_TCL
  932.         ok = Tcl_SetVar(Tkapp_Interp(self), name1, s, flags);
  933.         LEAVE_TCL
  934.     }
  935.     else {
  936.         PyErr_Clear();
  937.         if (PyArg_ParseTuple(args, "ssO:setvar", &name1, &name2, &newValue)) {
  938.             s = AsString (newValue, tmp);
  939.             ENTER_TCL
  940.             ok = Tcl_SetVar2(Tkapp_Interp(self), name1, name2, 
  941.                      s, flags);
  942.             LEAVE_TCL
  943.         }
  944.         else {
  945.             Py_DECREF(tmp);
  946.             return NULL;
  947.         }
  948.     }
  949.     Py_DECREF(tmp);
  950.  
  951.     if (!ok)
  952.         return Tkinter_Error(self);
  953.  
  954.     Py_INCREF(Py_None);
  955.     return Py_None;
  956. }
  957.  
  958. static PyObject *
  959. Tkapp_SetVar(self, args)
  960.     PyObject *self;
  961.     PyObject *args;
  962. {
  963.     return SetVar(self, args, TCL_LEAVE_ERR_MSG);
  964. }
  965.  
  966. static PyObject *
  967. Tkapp_GlobalSetVar(self, args)
  968.     PyObject *self;
  969.     PyObject *args;
  970. {
  971.     return SetVar(self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  972. }
  973.  
  974.  
  975.  
  976. static PyObject *
  977. GetVar(self, args, flags)
  978.     PyObject *self;
  979.     PyObject *args;
  980.     int flags;
  981. {
  982.     char *name1, *name2=NULL, *s;
  983.     PyObject *res = NULL;
  984.  
  985.     if (!PyArg_ParseTuple(args, "s|s:getvar", &name1, &name2))
  986.         return NULL;
  987.     ENTER_TCL
  988.     if (name2 == NULL)
  989.         s = Tcl_GetVar(Tkapp_Interp(self), name1, flags);
  990.  
  991.     else
  992.         s = Tcl_GetVar2(Tkapp_Interp(self), name1, name2, flags);
  993.     ENTER_OVERLAP
  994.  
  995.     if (s == NULL)
  996.         res = Tkinter_Error(self);
  997.     else
  998.         res = PyString_FromString(s);
  999.     LEAVE_OVERLAP_TCL
  1000.     return res;
  1001. }
  1002.  
  1003. static PyObject *
  1004. Tkapp_GetVar(self, args)
  1005.     PyObject *self;
  1006.     PyObject *args;
  1007. {
  1008.     return GetVar(self, args, TCL_LEAVE_ERR_MSG);
  1009. }
  1010.  
  1011. static PyObject *
  1012. Tkapp_GlobalGetVar(self, args)
  1013.     PyObject *self;
  1014.     PyObject *args;
  1015. {
  1016.     return GetVar(self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  1017. }
  1018.  
  1019.  
  1020.  
  1021. static PyObject *
  1022. UnsetVar(self, args, flags)
  1023.     PyObject *self;
  1024.     PyObject *args;
  1025.     int flags;
  1026. {
  1027.     char *name1, *name2=NULL;
  1028.     PyObject *res = NULL;
  1029.     int code;
  1030.  
  1031.     if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2))
  1032.         return NULL;
  1033.     ENTER_TCL
  1034.     if (name2 == NULL)
  1035.         code = Tcl_UnsetVar(Tkapp_Interp(self), name1, flags);
  1036.  
  1037.     else
  1038.         code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags);
  1039.     ENTER_OVERLAP
  1040.  
  1041.     if (code == TCL_ERROR)
  1042.         res = Tkinter_Error(self);
  1043.     else {
  1044.         Py_INCREF(Py_None);
  1045.         res = Py_None;
  1046.     }
  1047.     LEAVE_OVERLAP_TCL
  1048.     return res;
  1049. }
  1050.  
  1051. static PyObject *
  1052. Tkapp_UnsetVar(self, args)
  1053.     PyObject *self;
  1054.     PyObject *args;
  1055. {
  1056.     return UnsetVar(self, args, TCL_LEAVE_ERR_MSG);
  1057. }
  1058.  
  1059. static PyObject *
  1060. Tkapp_GlobalUnsetVar(self, args)
  1061.     PyObject *self;
  1062.     PyObject *args;
  1063. {
  1064.     return UnsetVar(self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
  1065. }
  1066.  
  1067.  
  1068.  
  1069. /** Tcl to Python **/
  1070.  
  1071. static PyObject *
  1072. Tkapp_GetInt(self, args)
  1073.     PyObject *self;
  1074.     PyObject *args;
  1075. {
  1076.     char *s;
  1077.     int v;
  1078.  
  1079.     if (!PyArg_ParseTuple(args, "s:getint", &s))
  1080.         return NULL;
  1081.     if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  1082.         return Tkinter_Error(self);
  1083.     return Py_BuildValue("i", v);
  1084. }
  1085.  
  1086. static PyObject *
  1087. Tkapp_GetDouble(self, args)
  1088.     PyObject *self;
  1089.     PyObject *args;
  1090. {
  1091.     char *s;
  1092.     double v;
  1093.  
  1094.     if (!PyArg_ParseTuple(args, "s:getdouble", &s))
  1095.         return NULL;
  1096.     if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  1097.         return Tkinter_Error(self);
  1098.     return Py_BuildValue("d", v);
  1099. }
  1100.  
  1101. static PyObject *
  1102. Tkapp_GetBoolean(self, args)
  1103.     PyObject *self;
  1104.     PyObject *args;
  1105. {
  1106.     char *s;
  1107.     int v;
  1108.  
  1109.     if (!PyArg_ParseTuple(args, "s:getboolean", &s))
  1110.         return NULL;
  1111.     if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
  1112.         return Tkinter_Error(self);
  1113.     return Py_BuildValue("i", v);
  1114. }
  1115.  
  1116. static PyObject *
  1117. Tkapp_ExprString(self, args)
  1118.     PyObject *self;
  1119.     PyObject *args;
  1120. {
  1121.     char *s;
  1122.     PyObject *res = NULL;
  1123.     int retval;
  1124.  
  1125.     if (!PyArg_ParseTuple(args, "s:exprstring", &s))
  1126.         return NULL;
  1127.     ENTER_TCL
  1128.     retval = Tcl_ExprString(Tkapp_Interp(self), s);
  1129.     ENTER_OVERLAP
  1130.     if (retval == TCL_ERROR)
  1131.         res = Tkinter_Error(self);
  1132.     else
  1133.         res = Py_BuildValue("s", Tkapp_Result(self));
  1134.     LEAVE_OVERLAP_TCL
  1135.     return res;
  1136. }
  1137.  
  1138. static PyObject *
  1139. Tkapp_ExprLong(self, args)
  1140.     PyObject *self;
  1141.     PyObject *args;
  1142. {
  1143.     char *s;
  1144.     PyObject *res = NULL;
  1145.     int retval;
  1146.     long v;
  1147.  
  1148.     if (!PyArg_ParseTuple(args, "s:exprlong", &s))
  1149.         return NULL;
  1150.     ENTER_TCL
  1151.     retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v);
  1152.     ENTER_OVERLAP
  1153.     if (retval == TCL_ERROR)
  1154.         res = Tkinter_Error(self);
  1155.     else
  1156.         res = Py_BuildValue("l", v);
  1157.     LEAVE_OVERLAP_TCL
  1158.     return res;
  1159. }
  1160.  
  1161. static PyObject *
  1162. Tkapp_ExprDouble(self, args)
  1163.     PyObject *self;
  1164.     PyObject *args;
  1165. {
  1166.     char *s;
  1167.     PyObject *res = NULL;
  1168.     double v;
  1169.     int retval;
  1170.  
  1171.     if (!PyArg_ParseTuple(args, "s:exprdouble", &s))
  1172.         return NULL;
  1173.     PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0)
  1174.     ENTER_TCL
  1175.     retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v);
  1176.     ENTER_OVERLAP
  1177.     PyFPE_END_PROTECT(retval)
  1178.     if (retval == TCL_ERROR)
  1179.         res = Tkinter_Error(self);
  1180.     else
  1181.         res = Py_BuildValue("d", v);
  1182.     LEAVE_OVERLAP_TCL
  1183.     return res;
  1184. }
  1185.  
  1186. static PyObject *
  1187. Tkapp_ExprBoolean(self, args)
  1188.     PyObject *self;
  1189.     PyObject *args;
  1190. {
  1191.     char *s;
  1192.     PyObject *res = NULL;
  1193.     int retval;
  1194.     int v;
  1195.  
  1196.     if (!PyArg_ParseTuple(args, "s:exprboolean", &s))
  1197.         return NULL;
  1198.     ENTER_TCL
  1199.     retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v);
  1200.     ENTER_OVERLAP
  1201.     if (retval == TCL_ERROR)
  1202.         res = Tkinter_Error(self);
  1203.     else
  1204.         res = Py_BuildValue("i", v);
  1205.     LEAVE_OVERLAP_TCL
  1206.     return res;
  1207. }
  1208.  
  1209.  
  1210.  
  1211. static PyObject *
  1212. Tkapp_SplitList(self, args)
  1213.     PyObject *self;
  1214.     PyObject *args;
  1215. {
  1216.     char *list;
  1217.     int argc;
  1218.     char **argv;
  1219.     PyObject *v;
  1220.     int i;
  1221.  
  1222.     if (!PyArg_ParseTuple(args, "s:splitlist", &list))
  1223.         return NULL;
  1224.  
  1225.     if (Tcl_SplitList(Tkapp_Interp(self), list, &argc, &argv) == TCL_ERROR)
  1226.         return Tkinter_Error(self);
  1227.  
  1228.     if (!(v = PyTuple_New(argc)))
  1229.         return NULL;
  1230.     
  1231.     for (i = 0; i < argc; i++) {
  1232.         PyObject *s = PyString_FromString(argv[i]);
  1233.         if (!s || PyTuple_SetItem(v, i, s)) {
  1234.             Py_DECREF(v);
  1235.             v = NULL;
  1236.             goto finally;
  1237.         }
  1238.     }
  1239.  
  1240.   finally:
  1241.     ckfree(FREECAST argv);
  1242.     return v;
  1243. }
  1244.  
  1245. static PyObject *
  1246. Tkapp_Split(self, args)
  1247.     PyObject *self;
  1248.     PyObject *args;
  1249. {
  1250.     char *list;
  1251.  
  1252.     if (!PyArg_ParseTuple(args, "s:split", &list))
  1253.         return NULL;
  1254.     return Split(list);
  1255. }
  1256.  
  1257. static PyObject *
  1258. Tkapp_Merge(self, args)
  1259.     PyObject *self;
  1260.     PyObject *args;
  1261. {
  1262.     char *s = Merge(args);
  1263.     PyObject *res = NULL;
  1264.  
  1265.     if (s) {
  1266.         res = PyString_FromString(s);
  1267.         ckfree(s);
  1268.     }
  1269.     else
  1270.         PyErr_SetString(Tkinter_TclError, "merge failed");
  1271.  
  1272.     return res;
  1273. }
  1274.  
  1275.  
  1276.  
  1277. /** Tcl Command **/
  1278.  
  1279. /* Client data struct */
  1280. typedef struct {
  1281.     PyObject *self;
  1282.     PyObject *func;
  1283. } PythonCmd_ClientData;
  1284.  
  1285. static int
  1286. PythonCmd_Error(interp)
  1287.     Tcl_Interp *interp;
  1288. {
  1289.     errorInCmd = 1;
  1290.     PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1291.     LEAVE_PYTHON
  1292.     return TCL_ERROR;
  1293. }
  1294.  
  1295. /* This is the Tcl command that acts as a wrapper for Python
  1296.  * function or method.
  1297.  */
  1298. static int
  1299. PythonCmd(clientData, interp, argc, argv)
  1300.     ClientData clientData;
  1301.     Tcl_Interp *interp;
  1302.     int argc;
  1303.     char *argv[];
  1304. {
  1305.     PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
  1306.     PyObject *self, *func, *arg, *res, *tmp;
  1307.     int i;
  1308.  
  1309.     ENTER_PYTHON
  1310.  
  1311.     /* TBD: no error checking here since we know, via the
  1312.      * Tkapp_CreateCommand() that the client data is a two-tuple
  1313.      */
  1314.     self = data->self;
  1315.     func = data->func;
  1316.  
  1317.     /* Create argument list (argv1, ..., argvN) */
  1318.     if (!(arg = PyTuple_New(argc - 1)))
  1319.         return PythonCmd_Error(interp);
  1320.  
  1321.     for (i = 0; i < (argc - 1); i++) {
  1322.         PyObject *s = PyString_FromString(argv[i + 1]);
  1323.         if (!s || PyTuple_SetItem(arg, i, s)) {
  1324.             Py_DECREF(arg);
  1325.             return PythonCmd_Error(interp);
  1326.         }
  1327.     }
  1328.     res = PyEval_CallObject(func, arg);
  1329.     Py_DECREF(arg);
  1330.  
  1331.     if (res == NULL)
  1332.         return PythonCmd_Error(interp);
  1333.  
  1334.     if (!(tmp = PyList_New(0))) {
  1335.         Py_DECREF(res);
  1336.         return PythonCmd_Error(interp);
  1337.     }
  1338.  
  1339.     Tcl_SetResult(Tkapp_Interp(self), AsString(res, tmp), TCL_VOLATILE);
  1340.     Py_DECREF(res);
  1341.     Py_DECREF(tmp);
  1342.  
  1343.     LEAVE_PYTHON
  1344.  
  1345.     return TCL_OK;
  1346. }
  1347.  
  1348. static void
  1349. PythonCmdDelete(clientData)
  1350.     ClientData clientData;
  1351. {
  1352.     PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
  1353.  
  1354.     ENTER_PYTHON
  1355.     Py_XDECREF(data->self);
  1356.     Py_XDECREF(data->func);
  1357.     PyMem_DEL(data);
  1358.     LEAVE_PYTHON
  1359. }
  1360.  
  1361.  
  1362.  
  1363. static PyObject *
  1364. Tkapp_CreateCommand(self, args)
  1365.     PyObject *self;
  1366.     PyObject *args;
  1367. {
  1368.     PythonCmd_ClientData *data;
  1369.     char *cmdName;
  1370.     PyObject *func;
  1371.     Tcl_Command err;
  1372.  
  1373.     if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func))
  1374.         return NULL;
  1375.     if (!PyCallable_Check(func)) {
  1376.         PyErr_SetString(PyExc_TypeError, "command not callable");
  1377.         return NULL;
  1378.     }
  1379.  
  1380.     data = PyMem_NEW(PythonCmd_ClientData, 1);
  1381.     if (!data)
  1382.         return NULL;
  1383.     Py_XINCREF(self);
  1384.     Py_XINCREF(func);
  1385.     data->self = self;
  1386.     data->func = func;
  1387.  
  1388.     ENTER_TCL
  1389.     err = Tcl_CreateCommand(Tkapp_Interp(self), cmdName, PythonCmd,
  1390.                 (ClientData)data, PythonCmdDelete);
  1391.     LEAVE_TCL
  1392.     if (err == NULL) {
  1393.         PyErr_SetString(Tkinter_TclError, "can't create Tcl command");
  1394.         PyMem_DEL(data);
  1395.         return NULL;
  1396.     }
  1397.  
  1398.     Py_INCREF(Py_None);
  1399.     return Py_None;
  1400. }
  1401.  
  1402.  
  1403.  
  1404. static PyObject *
  1405. Tkapp_DeleteCommand(self, args)
  1406.     PyObject *self;
  1407.     PyObject *args;
  1408. {
  1409.     char *cmdName;
  1410.     int err;
  1411.  
  1412.     if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
  1413.         return NULL;
  1414.     ENTER_TCL
  1415.     err = Tcl_DeleteCommand(Tkapp_Interp(self), cmdName);
  1416.     LEAVE_TCL
  1417.     if (err == -1) {
  1418.         PyErr_SetString(Tkinter_TclError, "can't delete Tcl command");
  1419.         return NULL;
  1420.     }
  1421.     Py_INCREF(Py_None);
  1422.     return Py_None;
  1423. }
  1424.  
  1425.  
  1426.  
  1427. #ifdef HAVE_CREATEFILEHANDLER
  1428. /** File Handler **/
  1429.  
  1430. typedef struct _fhcdata {
  1431.     PyObject *func;
  1432.     PyObject *file;
  1433.     int id;
  1434.     struct _fhcdata *next;
  1435. } FileHandler_ClientData;
  1436.  
  1437. static FileHandler_ClientData *HeadFHCD;
  1438.  
  1439. static FileHandler_ClientData *
  1440. NewFHCD(func, file, id)
  1441.     PyObject *func;
  1442.     PyObject *file;
  1443.     int id;
  1444. {
  1445.     FileHandler_ClientData *p;
  1446.     p = PyMem_NEW(FileHandler_ClientData, 1);
  1447.     if (p != NULL) {
  1448.         Py_XINCREF(func);
  1449.         Py_XINCREF(file);
  1450.         p->func = func;
  1451.         p->file = file;
  1452.         p->id = id;
  1453.         p->next = HeadFHCD;
  1454.         HeadFHCD = p;
  1455.     }
  1456.     return p;
  1457. }
  1458.  
  1459. static void
  1460. DeleteFHCD(id)
  1461.     int id;
  1462. {
  1463.     FileHandler_ClientData *p, **pp;
  1464.     
  1465.     pp = &HeadFHCD; 
  1466.     while ((p = *pp) != NULL) {
  1467.         if (p->id == id) {
  1468.             *pp = p->next;
  1469.             Py_XDECREF(p->func);
  1470.             Py_XDECREF(p->file);
  1471.             PyMem_DEL(p);
  1472.         }
  1473.         else
  1474.             pp = &p->next;
  1475.     }
  1476. }
  1477.  
  1478. static void
  1479. FileHandler(clientData, mask)
  1480.     ClientData clientData;
  1481.     int mask;
  1482. {
  1483.     FileHandler_ClientData *data = (FileHandler_ClientData *)clientData;
  1484.     PyObject *func, *file, *arg, *res;
  1485.  
  1486.     ENTER_PYTHON
  1487.     func = data->func;
  1488.     file = data->file;
  1489.  
  1490.     arg = Py_BuildValue("(Oi)", file, (long) mask);
  1491.     res = PyEval_CallObject(func, arg);
  1492.     Py_DECREF(arg);
  1493.  
  1494.     if (res == NULL) {
  1495.         errorInCmd = 1;
  1496.         PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1497.     }
  1498.     Py_XDECREF(res);
  1499.     LEAVE_PYTHON
  1500. }
  1501.  
  1502. static int
  1503. GetFileNo(file)
  1504.     /* Either an int >= 0 or an object with a
  1505.      *.fileno() method that returns an int >= 0
  1506.      */
  1507.     PyObject *file;
  1508. {
  1509.     PyObject *meth, *args, *res;
  1510.     int id;
  1511.     if (PyInt_Check(file)) {
  1512.         id = PyInt_AsLong(file);
  1513.         if (id < 0)
  1514.             PyErr_SetString(PyExc_ValueError, "invalid file id");
  1515.         return id;
  1516.     }
  1517.     args = PyTuple_New(0);
  1518.     if (args == NULL)
  1519.         return -1;
  1520.  
  1521.     meth = PyObject_GetAttrString(file, "fileno");
  1522.     if (meth == NULL) {
  1523.         Py_DECREF(args);
  1524.         return -1;
  1525.     }
  1526.  
  1527.     res = PyEval_CallObject(meth, args);
  1528.     Py_DECREF(args);
  1529.     Py_DECREF(meth);
  1530.     if (res == NULL)
  1531.         return -1;
  1532.  
  1533.     if (PyInt_Check(res))
  1534.         id = PyInt_AsLong(res);
  1535.     else
  1536.         id = -1;
  1537.  
  1538.     if (id < 0)
  1539.         PyErr_SetString(PyExc_ValueError,
  1540.                 "invalid fileno() return value");
  1541.     Py_DECREF(res);
  1542.     return id;
  1543. }
  1544.  
  1545. static PyObject *
  1546. Tkapp_CreateFileHandler(self, args)
  1547.     PyObject *self;
  1548.     PyObject *args;                 /* Is (file, mask, func) */
  1549. {
  1550.     FileHandler_ClientData *data;
  1551.     PyObject *file, *func;
  1552.     int mask, tfile;
  1553.  
  1554.     if (!PyArg_ParseTuple(args, "OiO:createfilehandler", &file, &mask, &func))
  1555.         return NULL;
  1556.     tfile = GetFileNo(file);
  1557.     if (tfile < 0)
  1558.         return NULL;
  1559.     if (!PyCallable_Check(func)) {
  1560.         PyErr_SetString(PyExc_TypeError, "bad argument list");
  1561.         return NULL;
  1562.     }
  1563.  
  1564.     data = NewFHCD(func, file, tfile);
  1565.     if (data == NULL)
  1566.         return NULL;
  1567.  
  1568.     /* Ought to check for null Tcl_File object... */
  1569.     ENTER_TCL
  1570.     Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data);
  1571.     LEAVE_TCL
  1572.     Py_INCREF(Py_None);
  1573.     return Py_None;
  1574. }
  1575.  
  1576. static PyObject *
  1577. Tkapp_DeleteFileHandler(self, args)
  1578.     PyObject *self;
  1579.     PyObject *args;                 /* Args: file */
  1580. {
  1581.     PyObject *file;
  1582.     FileHandler_ClientData *data;
  1583.     int tfile;
  1584.   
  1585.     if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file))
  1586.         return NULL;
  1587.     tfile = GetFileNo(file);
  1588.     if (tfile < 0)
  1589.         return NULL;
  1590.  
  1591.     DeleteFHCD(tfile);
  1592.  
  1593.     /* Ought to check for null Tcl_File object... */
  1594.     ENTER_TCL
  1595.     Tcl_DeleteFileHandler(tfile);
  1596.     LEAVE_TCL
  1597.     Py_INCREF(Py_None);
  1598.     return Py_None;
  1599. }
  1600. #endif /* HAVE_CREATEFILEHANDLER */
  1601.  
  1602.  
  1603. /**** Tktt Object (timer token) ****/
  1604.  
  1605. staticforward PyTypeObject Tktt_Type;
  1606.  
  1607. typedef struct {
  1608.     PyObject_HEAD
  1609.     Tcl_TimerToken token;
  1610.     PyObject *func;
  1611. } TkttObject;
  1612.  
  1613. static PyObject *
  1614. Tktt_DeleteTimerHandler(self, args)
  1615.     PyObject *self;
  1616.     PyObject *args;
  1617. {
  1618.     TkttObject *v = (TkttObject *)self;
  1619.     PyObject *func = v->func;
  1620.  
  1621.     if (!PyArg_ParseTuple(args, ":deletetimerhandler"))
  1622.         return NULL;
  1623.     if (v->token != NULL) {
  1624.         Tcl_DeleteTimerHandler(v->token);
  1625.         v->token = NULL;
  1626.     }
  1627.     if (func != NULL) {
  1628.         v->func = NULL;
  1629.         Py_DECREF(func);
  1630.         Py_DECREF(v); /* See Tktt_New() */
  1631.     }
  1632.     Py_INCREF(Py_None);
  1633.     return Py_None;
  1634. }
  1635.  
  1636. static PyMethodDef Tktt_methods[] =
  1637. {
  1638.     {"deletetimerhandler", Tktt_DeleteTimerHandler, 1},
  1639.     {NULL, NULL}
  1640. };
  1641.  
  1642. static TkttObject *
  1643. Tktt_New(func)
  1644.     PyObject *func;
  1645. {
  1646.     TkttObject *v;
  1647.   
  1648.     v = PyObject_New(TkttObject, &Tktt_Type);
  1649.     if (v == NULL)
  1650.         return NULL;
  1651.  
  1652.     Py_INCREF(func);
  1653.     v->token = NULL;
  1654.     v->func = func;
  1655.  
  1656.     /* Extra reference, deleted when called or when handler is deleted */
  1657.     Py_INCREF(v);
  1658.     return v;
  1659. }
  1660.  
  1661. static void
  1662. Tktt_Dealloc(self)
  1663.     PyObject *self;
  1664. {
  1665.     TkttObject *v = (TkttObject *)self;
  1666.     PyObject *func = v->func;
  1667.  
  1668.     Py_XDECREF(func);
  1669.  
  1670.     PyObject_Del(self);
  1671. }
  1672.  
  1673. static PyObject *
  1674. Tktt_Repr(self)
  1675.     PyObject *self;
  1676. {
  1677.     TkttObject *v = (TkttObject *)self;
  1678.     char buf[100];
  1679.  
  1680.     sprintf(buf, "<tktimertoken at 0x%lx%s>", (long)v,
  1681.         v->func == NULL ? ", handler deleted" : "");
  1682.     return PyString_FromString(buf);
  1683. }
  1684.  
  1685. static PyObject *
  1686. Tktt_GetAttr(self, name)
  1687.     PyObject *self;
  1688.     char *name;
  1689. {
  1690.     return Py_FindMethod(Tktt_methods, self, name);
  1691. }
  1692.  
  1693. static PyTypeObject Tktt_Type =
  1694. {
  1695.     PyObject_HEAD_INIT(NULL)
  1696.     0,                     /*ob_size */
  1697.     "tktimertoken",                 /*tp_name */
  1698.     sizeof(TkttObject),             /*tp_basicsize */
  1699.     0,                     /*tp_itemsize */
  1700.     Tktt_Dealloc,                 /*tp_dealloc */
  1701.     0,                     /*tp_print */
  1702.     Tktt_GetAttr,                 /*tp_getattr */
  1703.     0,                     /*tp_setattr */
  1704.     0,                     /*tp_compare */
  1705.     Tktt_Repr,                 /*tp_repr */
  1706.     0,                     /*tp_as_number */
  1707.     0,                     /*tp_as_sequence */
  1708.     0,                     /*tp_as_mapping */
  1709.     0,                     /*tp_hash */
  1710. };
  1711.  
  1712.  
  1713.  
  1714. /** Timer Handler **/
  1715.  
  1716. static void
  1717. TimerHandler(clientData)
  1718.     ClientData clientData;
  1719. {
  1720.     TkttObject *v = (TkttObject *)clientData;
  1721.     PyObject *func = v->func;
  1722.     PyObject *res;
  1723.  
  1724.     if (func == NULL)
  1725.         return;
  1726.  
  1727.     v->func = NULL;
  1728.  
  1729.     ENTER_PYTHON
  1730.  
  1731.     res  = PyEval_CallObject(func, NULL);
  1732.     Py_DECREF(func);
  1733.     Py_DECREF(v); /* See Tktt_New() */
  1734.  
  1735.     if (res == NULL) {
  1736.         errorInCmd = 1;
  1737.         PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
  1738.     }
  1739.     else
  1740.         Py_DECREF(res);
  1741.  
  1742.     LEAVE_PYTHON
  1743. }
  1744.  
  1745. static PyObject *
  1746. Tkapp_CreateTimerHandler(self, args)
  1747.     PyObject *self;
  1748.     PyObject *args;                 /* Is (milliseconds, func) */
  1749. {
  1750.     int milliseconds;
  1751.     PyObject *func;
  1752.     TkttObject *v;
  1753.  
  1754.     if (!PyArg_ParseTuple(args, "iO:createtimerhandler", &milliseconds, &func))
  1755.         return NULL;
  1756.     if (!PyCallable_Check(func)) {
  1757.         PyErr_SetString(PyExc_TypeError, "bad argument list");
  1758.         return NULL;
  1759.     }
  1760.     v = Tktt_New(func);
  1761.     v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
  1762.                       (ClientData)v);
  1763.  
  1764.     return (PyObject *) v;
  1765. }
  1766.  
  1767.  
  1768. /** Event Loop **/
  1769.  
  1770. static PyObject *
  1771. Tkapp_MainLoop(self, args)
  1772.     PyObject *self;
  1773.     PyObject *args;
  1774. {
  1775.     int threshold = 0;
  1776. #ifdef WITH_THREAD
  1777.     PyThreadState *tstate = PyThreadState_Get();
  1778. #endif
  1779.  
  1780.     if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold))
  1781.         return NULL;
  1782.  
  1783.     quitMainLoop = 0;
  1784.     while (Tk_GetNumMainWindows() > threshold &&
  1785.            !quitMainLoop &&
  1786.            !errorInCmd)
  1787.     {
  1788.         int result;
  1789.  
  1790. #ifdef WITH_THREAD
  1791.         Py_BEGIN_ALLOW_THREADS
  1792.         PyThread_acquire_lock(tcl_lock, 1);
  1793.         tcl_tstate = tstate;
  1794.         result = Tcl_DoOneEvent(TCL_DONT_WAIT);
  1795.         tcl_tstate = NULL;
  1796.         PyThread_release_lock(tcl_lock);
  1797.         if (result == 0)
  1798.             Sleep(20);
  1799.         Py_END_ALLOW_THREADS
  1800. #else
  1801.         result = Tcl_DoOneEvent(0);
  1802. #endif
  1803.  
  1804.         if (PyErr_CheckSignals() != 0)
  1805.             return NULL;
  1806.         if (result < 0)
  1807.             break;
  1808.     }
  1809.     quitMainLoop = 0;
  1810.  
  1811.     if (errorInCmd) {
  1812.         errorInCmd = 0;
  1813.         PyErr_Restore(excInCmd, valInCmd, trbInCmd);
  1814.         excInCmd = valInCmd = trbInCmd = NULL;
  1815.         return NULL;
  1816.     }
  1817.     Py_INCREF(Py_None);
  1818.     return Py_None;
  1819. }
  1820.  
  1821. static PyObject *
  1822. Tkapp_DoOneEvent(self, args)
  1823.     PyObject *self;
  1824.     PyObject *args;
  1825. {
  1826.     int flags = 0;
  1827.     int rv;
  1828.  
  1829.     if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags))
  1830.         return NULL;
  1831.  
  1832.     ENTER_TCL
  1833.     rv = Tcl_DoOneEvent(flags);
  1834.     LEAVE_TCL
  1835.     return Py_BuildValue("i", rv);
  1836. }
  1837.  
  1838. static PyObject *
  1839. Tkapp_Quit(self, args)
  1840.     PyObject *self;
  1841.     PyObject *args;
  1842. {
  1843.  
  1844.     if (!PyArg_ParseTuple(args, ":quit"))
  1845.         return NULL;
  1846.  
  1847.     quitMainLoop = 1;
  1848.     Py_INCREF(Py_None);
  1849.     return Py_None;
  1850. }
  1851.  
  1852. static PyObject *
  1853. Tkapp_InterpAddr(self, args)
  1854.     PyObject *self;
  1855.     PyObject *args;
  1856. {
  1857.  
  1858.     if (!PyArg_ParseTuple(args, ":interpaddr"))
  1859.         return NULL;
  1860.  
  1861.     return PyInt_FromLong((long)Tkapp_Interp(self));
  1862. }
  1863.  
  1864.  
  1865.  
  1866. /**** Tkapp Method List ****/
  1867.  
  1868. static PyMethodDef Tkapp_methods[] =
  1869. {
  1870.     {"call",            Tkapp_Call, 0},
  1871.     {"globalcall",            Tkapp_GlobalCall, 0},
  1872.     {"eval",            Tkapp_Eval, 1},
  1873.     {"globaleval",            Tkapp_GlobalEval, 1},
  1874.     {"evalfile",            Tkapp_EvalFile, 1},
  1875.     {"record",            Tkapp_Record, 1},
  1876.     {"adderrorinfo",       Tkapp_AddErrorInfo, 1},
  1877.     {"setvar",            Tkapp_SetVar, 1},
  1878.     {"globalsetvar",       Tkapp_GlobalSetVar, 1},
  1879.     {"getvar",            Tkapp_GetVar, 1},
  1880.     {"globalgetvar",       Tkapp_GlobalGetVar, 1},
  1881.     {"unsetvar",            Tkapp_UnsetVar, 1},
  1882.     {"globalunsetvar",     Tkapp_GlobalUnsetVar, 1},
  1883.     {"getint",            Tkapp_GetInt, 1},
  1884.     {"getdouble",            Tkapp_GetDouble, 1},
  1885.     {"getboolean",            Tkapp_GetBoolean, 1},
  1886.     {"exprstring",            Tkapp_ExprString, 1},
  1887.     {"exprlong",            Tkapp_ExprLong, 1},
  1888.     {"exprdouble",            Tkapp_ExprDouble, 1},
  1889.     {"exprboolean",        Tkapp_ExprBoolean, 1},
  1890.     {"splitlist",            Tkapp_SplitList, 1},
  1891.     {"split",            Tkapp_Split, 1},
  1892.     {"merge",            Tkapp_Merge, 0},
  1893.     {"createcommand",      Tkapp_CreateCommand, 1},
  1894.     {"deletecommand",      Tkapp_DeleteCommand, 1},
  1895. #ifdef HAVE_CREATEFILEHANDLER
  1896.     {"createfilehandler",  Tkapp_CreateFileHandler, 1},
  1897.     {"deletefilehandler",  Tkapp_DeleteFileHandler, 1},
  1898. #endif
  1899.     {"createtimerhandler", Tkapp_CreateTimerHandler, 1},
  1900.     {"mainloop",            Tkapp_MainLoop, 1},
  1901.     {"dooneevent",            Tkapp_DoOneEvent, 1},
  1902.     {"quit",            Tkapp_Quit, 1},
  1903.     {"interpaddr",         Tkapp_InterpAddr, 1},
  1904.     {NULL,                NULL}
  1905. };
  1906.  
  1907.  
  1908.  
  1909. /**** Tkapp Type Methods ****/
  1910.  
  1911. static void
  1912. Tkapp_Dealloc(self)
  1913.     PyObject *self;
  1914. {
  1915.     ENTER_TCL
  1916.     Tcl_DeleteInterp(Tkapp_Interp(self));
  1917.     LEAVE_TCL
  1918.     PyObject_Del(self);
  1919.     DisableEventHook();
  1920. }
  1921.  
  1922. static PyObject *
  1923. Tkapp_GetAttr(self, name)
  1924.     PyObject *self;
  1925.     char *name;
  1926. {
  1927.     return Py_FindMethod(Tkapp_methods, self, name);
  1928. }
  1929.  
  1930. static PyTypeObject Tkapp_Type =
  1931. {
  1932.     PyObject_HEAD_INIT(NULL)
  1933.     0,                     /*ob_size */
  1934.     "tkapp",                 /*tp_name */
  1935.     sizeof(TkappObject),             /*tp_basicsize */
  1936.     0,                     /*tp_itemsize */
  1937.     Tkapp_Dealloc,                 /*tp_dealloc */
  1938.     0,                     /*tp_print */
  1939.     Tkapp_GetAttr,                 /*tp_getattr */
  1940.     0,                     /*tp_setattr */
  1941.     0,                     /*tp_compare */
  1942.     0,                     /*tp_repr */
  1943.     0,                     /*tp_as_number */
  1944.     0,                     /*tp_as_sequence */
  1945.     0,                     /*tp_as_mapping */
  1946.     0,                     /*tp_hash */
  1947. };
  1948.  
  1949.  
  1950.  
  1951. /**** Tkinter Module ****/
  1952.  
  1953. static PyObject *
  1954. Tkinter_Create(self, args)
  1955.     PyObject *self;
  1956.     PyObject *args;
  1957. {
  1958.     char *screenName = NULL;
  1959.     char *baseName = NULL;
  1960.     char *className = NULL;
  1961.     int interactive = 0;
  1962.  
  1963.     baseName = strrchr(Py_GetProgramName(), '/');
  1964.     if (baseName != NULL)
  1965.         baseName++;
  1966.     else
  1967.         baseName = Py_GetProgramName();
  1968.     className = "Tk";
  1969.   
  1970.     if (!PyArg_ParseTuple(args, "|zssi:create",
  1971.                   &screenName, &baseName, &className,
  1972.                   &interactive))
  1973.         return NULL;
  1974.  
  1975.     return (PyObject *) Tkapp_New(screenName, baseName, className, 
  1976.                       interactive);
  1977. }
  1978.  
  1979. static PyMethodDef moduleMethods[] =
  1980. {
  1981.     {"create",             Tkinter_Create, 1},
  1982. #ifdef HAVE_CREATEFILEHANDLER
  1983.     {"createfilehandler",  Tkapp_CreateFileHandler, 1},
  1984.     {"deletefilehandler",  Tkapp_DeleteFileHandler, 1},
  1985. #endif
  1986.     {"createtimerhandler", Tkapp_CreateTimerHandler, 1},
  1987.     {"mainloop",           Tkapp_MainLoop, 1},
  1988.     {"dooneevent",         Tkapp_DoOneEvent, 1},
  1989.     {"quit",               Tkapp_Quit, 1},
  1990.     {NULL,                 NULL}
  1991. };
  1992.  
  1993. #ifdef WAIT_FOR_STDIN
  1994.  
  1995. static int stdin_ready = 0;
  1996.  
  1997. #ifndef MS_WINDOWS
  1998. static void
  1999. MyFileProc(clientData, mask)
  2000.     void *clientData;
  2001.     int mask;
  2002. {
  2003.     stdin_ready = 1;
  2004. }
  2005. #endif
  2006.  
  2007. static PyThreadState *event_tstate = NULL;
  2008.  
  2009. static int
  2010. EventHook()
  2011. {
  2012. #ifndef MS_WINDOWS
  2013.     int tfile;
  2014. #endif
  2015. #ifdef WITH_THREAD
  2016.     PyEval_RestoreThread(event_tstate);
  2017. #endif
  2018.     stdin_ready = 0;
  2019.     errorInCmd = 0;
  2020. #ifndef MS_WINDOWS
  2021.     tfile = fileno(stdin);
  2022.     Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL);
  2023. #endif
  2024.     while (!errorInCmd && !stdin_ready) {
  2025.         int result;
  2026. #ifdef MS_WINDOWS
  2027.         if (_kbhit()) {
  2028.             stdin_ready = 1;
  2029.             break;
  2030.         }
  2031. #endif
  2032. #if defined(WITH_THREAD) || defined(MS_WINDOWS)
  2033.         Py_BEGIN_ALLOW_THREADS
  2034.         PyThread_acquire_lock(tcl_lock, 1);
  2035.         tcl_tstate = event_tstate;
  2036.  
  2037.         result = Tcl_DoOneEvent(TCL_DONT_WAIT);
  2038.  
  2039.         tcl_tstate = NULL;
  2040.         PyThread_release_lock(tcl_lock);
  2041.         if (result == 0)
  2042.             Sleep(20);
  2043.         Py_END_ALLOW_THREADS
  2044. #else
  2045.         result = Tcl_DoOneEvent(0);
  2046. #endif
  2047.  
  2048.         if (result < 0)
  2049.             break;
  2050.     }
  2051. #ifndef MS_WINDOWS
  2052.     Tcl_DeleteFileHandler(tfile);
  2053. #endif
  2054.     if (errorInCmd) {
  2055.         errorInCmd = 0;
  2056.         PyErr_Restore(excInCmd, valInCmd, trbInCmd);
  2057.         excInCmd = valInCmd = trbInCmd = NULL;
  2058.         PyErr_Print();
  2059.     }
  2060. #ifdef WITH_THREAD
  2061.     PyEval_SaveThread();
  2062. #endif
  2063.     return 0;
  2064. }
  2065.  
  2066. #endif
  2067.  
  2068. static void
  2069. EnableEventHook()
  2070. {
  2071. #ifdef WAIT_FOR_STDIN
  2072.     if (PyOS_InputHook == NULL) {
  2073. #ifdef WITH_THREAD
  2074.         event_tstate = PyThreadState_Get();
  2075. #endif
  2076.         PyOS_InputHook = EventHook;
  2077.     }
  2078. #endif
  2079. }
  2080.  
  2081. static void
  2082. DisableEventHook()
  2083. {
  2084. #ifdef WAIT_FOR_STDIN
  2085.     if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) {
  2086.         PyOS_InputHook = NULL;
  2087.     }
  2088. #endif
  2089. }
  2090.  
  2091.  
  2092. /* all errors will be checked in one fell swoop in init_tkinter() */
  2093. static void
  2094. ins_long(d, name, val)
  2095.     PyObject *d;
  2096.     char *name;
  2097.     long val;
  2098. {
  2099.     PyObject *v = PyInt_FromLong(val);
  2100.     if (v) {
  2101.         PyDict_SetItemString(d, name, v);
  2102.         Py_DECREF(v);
  2103.     }
  2104. }
  2105. static void
  2106. ins_string(d, name, val)
  2107.     PyObject *d;
  2108.     char *name;
  2109.     char *val;
  2110. {
  2111.     PyObject *v = PyString_FromString(val);
  2112.     if (v) {
  2113.         PyDict_SetItemString(d, name, v);
  2114.         Py_DECREF(v);
  2115.     }
  2116. }
  2117.  
  2118.  
  2119. DL_EXPORT(void)
  2120. init_tkinter()
  2121. {
  2122.     PyObject *m, *d;
  2123.  
  2124.     Tkapp_Type.ob_type = &PyType_Type;
  2125.  
  2126. #ifdef WITH_THREAD
  2127.     tcl_lock = PyThread_allocate_lock();
  2128. #endif
  2129.  
  2130.     m = Py_InitModule("_tkinter", moduleMethods);
  2131.  
  2132.     d = PyModule_GetDict(m);
  2133.     Tkinter_TclError = Py_BuildValue("s", "TclError");
  2134.     PyDict_SetItemString(d, "TclError", Tkinter_TclError);
  2135.  
  2136.     ins_long(d, "READABLE", TCL_READABLE);
  2137.     ins_long(d, "WRITABLE", TCL_WRITABLE);
  2138.     ins_long(d, "EXCEPTION", TCL_EXCEPTION);
  2139.     ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS);
  2140.     ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS);
  2141.     ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS);
  2142.     ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS);
  2143.     ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS);
  2144.     ins_long(d, "DONT_WAIT", TCL_DONT_WAIT);
  2145.     ins_string(d, "TK_VERSION", TK_VERSION);
  2146.     ins_string(d, "TCL_VERSION", TCL_VERSION);
  2147.  
  2148.     PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type);
  2149.  
  2150.     Tktt_Type.ob_type = &PyType_Type;
  2151.     PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
  2152.  
  2153.     /* This helps the dynamic loader; in Unicode aware Tcl versions
  2154.        it also helps Tcl find its encodings. */
  2155.     Tcl_FindExecutable(Py_GetProgramName());
  2156.  
  2157.     if (PyErr_Occurred())
  2158.         return;
  2159.  
  2160. #if 0
  2161.     /* This was not a good idea; through <Destroy> bindings,
  2162.        Tcl_Finalize() may invoke Python code but at that point the
  2163.        interpreter and thread state have already been destroyed! */
  2164.     Py_AtExit(Tcl_Finalize);
  2165. #endif
  2166.  
  2167. #ifdef macintosh
  2168.     /*
  2169.     ** Part of this code is stolen from MacintoshInit in tkMacAppInit.
  2170.     ** Most of the initializations in that routine (toolbox init calls and
  2171.     ** such) have already been done for us, so we only need these.
  2172.     */
  2173.     tcl_macQdPtr = &qd;
  2174.  
  2175.     Tcl_MacSetEventProc(PyMacConvertEvent);
  2176. #if GENERATINGCFM
  2177.     mac_addlibresources();
  2178. #endif /* GENERATINGCFM */
  2179. #endif /* macintosh */
  2180. }
  2181.  
  2182.  
  2183.  
  2184. #ifdef macintosh
  2185.  
  2186. /*
  2187. ** Anyone who embeds Tcl/Tk on the Mac must define panic().
  2188. */
  2189.  
  2190. void
  2191. panic(char * format, ...)
  2192. {
  2193.     va_list varg;
  2194.     
  2195.     va_start(varg, format);
  2196.     
  2197.     vfprintf(stderr, format, varg);
  2198.     (void) fflush(stderr);
  2199.     
  2200.     va_end(varg);
  2201.  
  2202.     Py_FatalError("Tcl/Tk panic");
  2203. }
  2204.  
  2205. /*
  2206. ** Pass events to SIOUX before passing them to Tk.
  2207. */
  2208.  
  2209. static int
  2210. PyMacConvertEvent(eventPtr)
  2211.     EventRecord *eventPtr;
  2212. {
  2213.     WindowPtr frontwin;
  2214.     /*
  2215.     ** Sioux eats too many events, so we don't pass it everything.  We
  2216.     ** always pass update events to Sioux, and we only pass other events if
  2217.     ** the Sioux window is frontmost. This means that Tk menus don't work
  2218.     ** in that case, but at least we can scroll the sioux window.
  2219.     ** Note that the SIOUXIsAppWindow() routine we use here is not really
  2220.     ** part of the external interface of Sioux...
  2221.     */
  2222.     frontwin = FrontWindow();
  2223.     if ( eventPtr->what == updateEvt || SIOUXIsAppWindow(frontwin) ) {
  2224.         if (SIOUXHandleOneEvent(eventPtr))
  2225.             return 0; /* Nothing happened to the Tcl event queue */
  2226.     }
  2227.     return TkMacConvertEvent(eventPtr);
  2228. }
  2229.  
  2230. #if GENERATINGCFM
  2231.  
  2232. /*
  2233. ** Additional Mac specific code for dealing with shared libraries.
  2234. */
  2235.  
  2236. #include <Resources.h>
  2237. #include <CodeFragments.h>
  2238.  
  2239. static int loaded_from_shlib = 0;
  2240. static FSSpec library_fss;
  2241.  
  2242. /*
  2243. ** If this module is dynamically loaded the following routine should
  2244. ** be the init routine. It takes care of adding the shared library to
  2245. ** the resource-file chain, so that the tk routines can find their
  2246. ** resources.
  2247. */
  2248. OSErr pascal
  2249. init_tkinter_shlib(CFragInitBlockPtr data)
  2250. {
  2251.     __initialize();
  2252.     if ( data == nil ) return noErr;
  2253.     if ( data->fragLocator.where == kDataForkCFragLocator ) {
  2254.         library_fss = *data->fragLocator.u.onDisk.fileSpec;
  2255.         loaded_from_shlib = 1;
  2256.     } else if ( data->fragLocator.where == kResourceCFragLocator ) {
  2257.         library_fss = *data->fragLocator.u.inSegs.fileSpec;
  2258.         loaded_from_shlib = 1;
  2259.     }
  2260.     return noErr;
  2261. }
  2262.  
  2263. /*
  2264. ** Insert the library resources into the search path. Put them after
  2265. ** the resources from the application. Again, we ignore errors.
  2266. */
  2267. static
  2268. mac_addlibresources()
  2269. {
  2270.     if ( !loaded_from_shlib ) 
  2271.         return;
  2272.     (void)FSpOpenResFile(&library_fss, fsRdPerm);
  2273. }
  2274.  
  2275. #endif /* GENERATINGCFM */
  2276. #endif /* macintosh */
  2277.